<?php
class Admin_Model_DbTable_Permission extends Zend_Db_Table_Abstract {
	protected $_name = 'permission';
	public function addPermission($admin_id, $them, $sua, $xoa, $description, $status) {
		$data = array (
				'ADMIN_ID' => $admin_id,
				'THEM' => $them,
				'CHINH_SUA' => $sua,
				'XOA' => $xoa,
				'DESCRIPTION' => $description,
				'STATUS' => $status 
		);
		return $this->insert ( $data );
	}
	public function updatePermission($id, $admin_id, $them, $sua, $xoa, $description, $status) {
		$data = array (
				'ADMIN_ID' => $admin_id,
				'THEM' => $them,
				'CHINH_SUA' => $sua,
				'XOA' => $xoa,
				'DESCRIPTION' => $description,
				'STATUS' => $status 
		);
		return $this->update ( $data, "ID = $id" );
	}
	public function updateStatus($id, $status) {
		$data = array (
				'' => $status 
		);
		return $this->update ( $data, "ID = $id" );
	}
	public function removePermission($id) {
		return $this->delete ( "ID = $id" );
	}
	public function activePermission($id) {
		$lv = $this->fetchRow ( "ID = $id" );
		if ($lv ["STATUS"] == 1) {
			$this->update ( array (
					"STATUS" => 0 
			), "ID = $id" );
		} else {
			$this->update ( array (
					"STATUS" => 1 
			), "ID = $id" );
		}
	}
	public function getPermissionByRoleId($role_id) {
		$select = $this->select ( Zend_Db_Table::SELECT_WITH_FROM_PART )->setIntegrityCheck ( false );
		
		$rows = NULL;
		
		$select->from ( "permission AS pe", array (
				"pe.ID",
				"pe.THEM",
				"pe.CHINH_SUA",
				"pe.XOA",
				"pe.DESCRIPTION",
				"pe.STATUS" 
		) )->where ( "pe.STATUS = ?", 1 )->join ( "role AS r", "r.ID = pe.ROLE_ID", array (
				"r.ROLE_NAME" 
		) )->where ( "pe.ROLE_ID = ?", $role_id );
		try {
			$rows = $this->fetchRow ( $select );
		} catch ( Exception $e ) {
			print_r ( $e );
		}
		
		return $rows->toArray ();
		// return $this->fetchRow ( "ROLE_ID = $role_id" )->toArray ();
	}
	public function getAllPermission() {
		return $this->fetchAll ()->toArray ();
	}
	public function getPermissionById($id) {
		return $this->fetchRow ( "ID = $id AND STATUS = 1" )->toArray ();
	}
	public function getPermissionByRoleName($role_name) {
		$select = $this->select ( Zend_Db_Table::SELECT_WITH_FROM_PART )->setIntegrityCheck ( false );
		
		$rows = NULL;
		
		$select->from ( "permission AS pe", array (
				"pe.ID",
				"pe.THEM",
				"pe.CHINH_SUA",
				"pe.XOA",
				"pe.DESCRIPTION",
				"pe.STATUS" 
		) )->where ( "pe.STATUS = ?", 1 )->join ( "role AS r", "r.ID = pe.ROLE_ID", array (
				"r.ROLE_NAME" 
		) )->where ( "r.ROLE_NAME = ?", $role_name );
		try {
			$rows = $this->fetchRow ( $select );
		} catch ( Exception $e ) {
			print_r ( $e );
		}
		
		return $rows->toArray ();
	}
}

